<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';

import {
  Button,
  Checkbox,
  CheckboxGroup,
  Divider,
  InputNumber,
  message,
  RadioButton,
  RadioGroup,
} from 'ant-design-vue';

import { updateCalendarRoomPrice } from '#/api';
import { useRoomList } from '#/hooks/useRoomList';

import CalendarList from '../house-count/components/CalendarList.vue';
import DateSelect from '../house-count/components/DateSelect.vue';

const { roomList, fetchRoomList } = useRoomList();

// 表单接口类型
interface FormDataType {
  priceType: number | string;
  weekendsPrice: number | string;
  weekType: number[] | string[];
  allWeekType: boolean;
  timeType: number | string;
  roomSelect: number[];
  allRoomSelect: boolean;
  unityPrice: number | string;
}

const formData = ref<FormDataType>({
  priceType: '0', // 设置价格类型 0分开改价 1统一加减
  weekendsPrice: '0', // 是否区分周末价格 0否 1是
  weekType: ['1', '2', '3', '4', '5', '6', '0'], // 星期类型
  allWeekType: true, // 是否全选
  timeType: '1', // 时间类型 1时间区间 2日历选择模式
  roomSelect: [], // 选择的房型
  allRoomSelect: false, // 是否全选房型
  unityPrice: '', // 统一改价
});

const optionsWeek = [
  { label: '周一', value: '1' },
  { label: '周二', value: '2' },
  { label: '周三', value: '3' },
  { label: '周四', value: '4' },
  { label: '周五', value: '5' },
  { label: '周六', value: '6' },
  { label: '周日', value: '0' },
];

// 全选星期事件
const handleAll = (e: any) => {
  Object.assign(formData.value, {
    weekType: e.target.checked ? optionsWeek.map((item) => item.value) : [],
  });
};
// 监听是否全选事件
watch(
  () => formData.value.weekType,
  (val) => {
    formData.value.allWeekType = val.length === optionsWeek.length;
  },
  { immediate: true },
);

interface RoomSelectItem {
  sellPrice: number;
  price: string;
  roomId: any;
  nameZh: string | undefined;
}
const roomSelectList = ref<RoomSelectItem[]>([]);
const priceList = computed(() => {
  return roomSelectList.value.map((item) => {
    return {
      price: item.price,
      roomTypeId: item.roomId,
    };
  });
});

// 房型选择
const handleRoomSelect = (e: any[]) => {
  const arr = e.map((item) => item);

  // 将 e 中的元素转换为 number 类型
  const numberE = arr.map(Number);
  const currentRoomSelect = new Set(formData.value.roomSelect);
  const newRoomSelect = new Set(numberE);
  // 找出需要添加的 id
  const toAdd = [...newRoomSelect].filter(
    (id): id is number => typeof id === 'number' && !currentRoomSelect.has(id),
  );
  // 找出需要删除的 id
  const toRemove = [...currentRoomSelect].filter(
    (id): id is number => typeof id === 'number' && !newRoomSelect.has(id),
  );

  // 添加新选中的房型
  toAdd.forEach((id) => {
    const item = {
      sellPrice: roomList.value?.find((item) => item.id === id)?.sellPrice || 0,
      price: '',
      roomId: id,
      nameZh: roomList.value?.find((item) => item.id === id)?.nameZh || '',
    };
    formData.value.roomSelect.push(id);
    roomSelectList.value.push(item);
  });

  // 删除取消选中的房型
  toRemove.forEach((id) => {
    const index = formData.value.roomSelect.indexOf(id);
    if (index !== -1) {
      formData.value.roomSelect.splice(index, 1);
      roomSelectList.value.splice(index, 1);
    }
  });

  formData.value.allRoomSelect =
    roomList.value.length === formData.value.roomSelect.length;
};

// 删除表单中的房型选择与formData中的房型选择
const handleDelete = (e: any) => {
  const index = roomSelectList.value.findIndex(
    (item) => item.roomId === e.roomId,
  );
  if (index !== -1) {
    roomSelectList.value.splice(index, 1);
  }
  const index2 = formData.value.roomSelect.indexOf(e.roomId);
  if (index2 !== -1) {
    formData.value.roomSelect.splice(index2, 1);
  }
  formData.value.allRoomSelect = false;
};

// 房型全选事件
const handleRoomAll = (e: any) => {
  Object.assign(formData.value, {
    roomSelect: e.target.checked ? roomList.value?.map((item) => item.id) : [],
  });
  // 全选和反选事件
  roomSelectList.value =
    formData.value.roomSelect.length === 0
      ? []
      : formData.value.roomSelect.map((item) => {
          return {
            sellPrice:
              roomList.value?.find((i) => i.id === item)?.sellPrice || 0,
            price: '',
            roomId: item,
            nameZh: roomList.value?.find((i) => i.id === item)?.nameZh || '',
          };
        });
};
watch(
  () => formData.value.roomSelect,
  (val) => {
    formData.value.allRoomSelect = val.length === roomList.value.length;
  },
);

// 统一修改卖价
const handleUnityPrice = (e: any) => {
  roomSelectList.value.forEach((item) => {
    // 统一更改原价
    item.price = e || '';
  });
};

// 选中的日期数据
const dateArr = ref<string[]>([]);
// 日历模式选中日期事件
const dateChange = (val: string[]) => {
  dateArr.value = val || [];
};
const loading = ref(false);
// 保存事件
const submit = async () => {
  if (formData.value.roomSelect.length === 0) {
    return message.error('请选择房型');
  }
  if (dateArr.value.length === 0) {
    return message.error('请选择日期');
  }
  if (loading.value) return;
  loading.value = true;
  try {
    await updateCalendarRoomPrice({
      priceList: priceList.value || [],
      timeList: dateArr.value,
    });
    // 清空选中的房型
    Object.assign(formData.value, {
      roomSelect: [],
    });
    loading.value = false;
    roomSelectList.value = [];
    message.success('保存成功');
  } catch (error) {
    loading.value = false;
    console.error('保存失败：', error);
  }
};

onMounted(async () => {
  await fetchRoomList({
    enableStatus: true,
    name: '',
  });
});
</script>

<template>
  <div class="flex h-[100%] w-[100%] flex-col overflow-auto p-5 pt-4">
    <div class="mb-4 text-xl font-bold">批量修改房价</div>
    <div class="card-box w-full p-5 pt-4">
      <div class="mb-3 text-base font-bold">选择房型</div>
      <div class="card-box rounded-md">
        <div class="flex min-h-[50px] items-center px-5 py-3">
          <Checkbox
            v-model:checked="formData.allRoomSelect"
            @change="handleRoomAll"
          >
            <div class="text flex items-center">
              全选
              <p v-if="formData.roomSelect.length > 0" class="ml-2">
                (已选择<span class="text-primary pl-1">
                  {{ formData.roomSelect.length }}
                </span>
                个房型)
              </p>
            </div>
          </Checkbox>
        </div>
        <div class="max-h-[240px] overflow-auto px-5">
          <CheckboxGroup
            :value="formData.roomSelect"
            class="flex flex-wrap"
            name="roomSelect"
            @change="handleRoomSelect"
          >
            <div v-for="item in roomList" :key="item.id" class="w-full">
              <Divider class="m-0" />
              <Checkbox
                :value="item.id"
                class="mr-2 flex min-h-[50px] items-center py-3"
              >
                <span class="text">{{ item.nameZh }}</span>
              </Checkbox>
            </div>
          </CheckboxGroup>
        </div>
      </div>

      <div class="mb-3 mt-4 text-base font-bold">选择日期</div>
      <div class="card-box rounded-md">
        <div class="flex min-h-[50px] flex-wrap items-center px-5 py-3">
          <RadioGroup v-model:value="formData.timeType">
            <RadioButton class="h-auto py-1" value="1">
              <span :class="[formData.timeType === '1' ? 'font-bold' : 'text']">
                多段模式
              </span>
            </RadioButton>
            <RadioButton class="h-auto py-1" value="2">
              <span :class="[formData.timeType === '2' ? 'font-bold' : 'text']">
                日历模式
              </span>
            </RadioButton>
          </RadioGroup>
        </div>
        <Divider class="m-0" />
        <div v-if="formData.timeType === '1'" class="w-full">
          <DateSelect
            :select-week="formData.weekType"
            :show-scope="false"
            @change="dateChange"
          />
        </div>
        <div v-else class="w-full">
          <CalendarList :select-week="formData.weekType" @change="dateChange" />
        </div>
        <Divider class="m-0" />
        <div class="flex min-h-[50px] flex-wrap items-center px-5">
          <div class="w-[90px] py-1 pr-2 opacity-60">适用星期</div>
          <div class="flex-auto py-2">
            <CheckboxGroup v-model:value="formData.weekType" name="weekType">
              <Checkbox
                v-for="item in optionsWeek"
                :key="item.value"
                :value="item.value"
                class="mr-2 py-1"
              >
                <span class="text">{{ item.label }}</span>
              </Checkbox>
            </CheckboxGroup>
            <Checkbox
              v-model:checked="formData.allWeekType"
              @change="handleAll"
            >
              <span class="text">全选</span>
            </Checkbox>
          </div>
        </div>
      </div>

      <div class="mb-3 mt-4 text-base font-bold">设置价格</div>
      <div class="card-box rounded-md">
        <div class="overflow-x-auto">
          <!-- 设置价格表单 -->
          <ul
            class="flex w-full min-w-[1100px] items-center justify-between bg-gray-200 bg-opacity-40 py-2.5"
          >
            <li class="w-[42%] min-w-[300px] flex-auto px-3">产品名称</li>
            <li class="w-[24%] min-w-[80px] flex-auto px-3">原卖价</li>
            <li class="w-[24%] min-w-[180px] flex-auto px-3">卖价</li>
            <li class="w-[10%] min-w-[80px] px-2 text-center">操作</li>
          </ul>
          <ul class="flex w-full min-w-[1100px] items-center justify-between">
            <li class="text-primary w-[42%] min-w-[300px] flex-auto px-3">
              批量改价
            </li>
            <li class="w-[24%] min-w-[80px] flex-auto px-3"></li>
            <li class="w-[24%] min-w-[180px] flex-auto p-3">
              <InputNumber
                v-model:value="formData.unityPrice"
                :max="999999"
                :min="0"
                style="width: 120px"
                @change="handleUnityPrice"
              />
            </li>
            <li class="w-[10%] min-w-[80px] px-2"></li>
          </ul>
          <div>
            <ul
              v-for="item in roomSelectList"
              :key="item.roomId"
              class="flex w-full min-w-[1100px] items-center justify-between border-t"
            >
              <li class="w-[42%] min-w-[300px] flex-auto px-3">
                {{ item.nameZh || '' }}
              </li>
              <li class="w-[24%] min-w-[80px] flex-auto px-3">
                {{ item.sellPrice || 0 }}
              </li>
              <li class="w-[24%] min-w-[180px] flex-auto p-3">
                <InputNumber
                  v-model:value="item.price"
                  :max="999999"
                  :min="0"
                  prefix="￥"
                  style="width: 120px"
                />
              </li>
              <li
                class="flex w-[10%] min-w-[80px] items-center justify-center px-2"
              >
                <Button type="link" @click="handleDelete(item)">删除</Button>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <Button
        :disabled="formData.roomSelect.length === 0 || dateArr.length === 0"
        :loading="loading"
        class="mb-4 mt-5 h-auto w-auto px-14 py-2"
        type="primary"
        @click="submit"
      >
        保存
      </Button>
    </div>
  </div>
</template>
<style scoped lang="scss">
.text {
  color: hsl(var(--card-foreground));
}
</style>
